<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/


namespace Login\Model;
use Think\Model;

class MemberModel extends Model {
	
	//提交登录
	function LoginSubmit(){
		
		if($this->uid>0){
			$this->error='对不起!您已登录过了';
			return false;
		}

		if (!IS_POST){
			$this->error='对不起!没有数据请求！';
			return false;
		}
		
		//表单验证
		if (!$this->autoCheckToken($_POST)){
			//$this->error='表单验证失败！刷新页面后重试！';
			//return false;
		}
		
		if(empty($_POST['mobilecode'])){
			require(FOXPHP_PATH."/Apps/Hook/GeeTest/geetest.php");
			$geetest = new \Geetest();
			$geetest->set_privatekey(C('Geetest_Key'));
		
			if(isset($_POST['geetest_challenge']) && isset($_POST['geetest_validate']) && isset($_POST['geetest_seccode'])) {
				$result = $geetest->validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode']);
				if ($result == FALSE) {
					$this->error='对不起!验证码有误！';
					return false;
				} 
			}else{
				$verify = new \Think\Verify();
				if(!$verify->check($_POST['seccode'])){
					$this->error='对不起!验证码有误！！';
					return false;
				}
			}
		}
	 
		if($uid=$this->LoginCheck()){
			return $uid;
		}else{
			return false;
		}
		
	}
	
	function SetCookieCode($uid=0,$cookiecode=0,$username=''){
		return iconv_substr(md5($uid.$cookiecode.$username.$uid),0,16,C('S_CHARSET'));
	}
	
	function Callback(){
		return $this->callback;
	}
	
	function MobileSecurityCheck($uid=0,$userarray){
		$uid=intval($uid);
		$certificate=M('MemberCertificate')->token(false)->where(" uid=$uid AND type=2 AND status=5 ")->find();
		if($certificate['uid']){
			$mobile=$certificate['mobile'];
			$mobileconsume=M('MobileConsume')->token(false)->where(" uid=$uid AND mobile='$mobile' ")->order('datetime DESC')->find();

			if($_POST['mobilecode']){
				
				if(intval($mobileconsume['sendcode'])==$_POST['mobilecode']){
					return true;
				}else{
					$this->error='对不起!手机验证码有误!';
					return false;
				}
				
			}elseif(!$_POST['mobilecode']){

				if($mobileconsume['datetime']>0 && (intval($mobileconsume['datetime'])+600)>time()){
					$this->error='手机验证码已发送!请输入验证！未收到请10分钟后再试试！';
					return false;
				}
	
				$sendcode=RandomText(6,2);
				$sendsms=array(
					  
					//接收
					'smsuid'=>$userarray['uid'],
					
					//接收用户名
					'smsusername'=>$userarray['username'],
					
					//接收手机
					'smsmobile'=>$certificate['mobile'],
					
					//验证码
					'smssendcode'=>$sendcode,
					
					//手机内容
					'smscontent'=>'验证码：'.$sendcode.' 请在页面上输入验证码完成操作。非本人操作,请忽略本信息。'
				);
				
				require_once(C('S_APPS')."/Hook/SendSMS/FoxSendSMS.php");
				$sendsms = new \MobileSMS($sendsms);		
				$sendsms->SendSMS();

				
				$this->error='请输入手机验证码！';
				return false;
			}
		}
		
		$this->error='手机未认证！';
		return false;
	}
	
	function MobileSecurity($uid,$userarray,$type='loginsecurity'){
		if($type=='loginsecurity' && intval($userarray['loginsecurity'])==1 && $uid>0){
			if($this->MobileSecurityCheck($uid,$userarray)){
				return true;
			}else{
				return false;
			}
		}elseif($type=='paysecurity' && intval($userarray['paysecurity'])==1 && $uid>0){	
			if($this->MobileSecurityCheck($uid,$userarray)){
				return true;
			}else{
				return false;
			}
		}else{
			if(!empty($_POST['mobilecode'])){
				$this->error='对不起!手机验证码有误!';
				return false;
			}
		}
		
		return true;
	}
	
	function LoginCheck(){
	
		if($this->LoginError(1)==false){
			return false;
		}
	
		$membercertificate=new \MemberCertificate\Model\MemberCertificateModel();
		
		if(IsNum($_POST['username'])){
			//手机
			$mobile=$_POST['username'];
			if($membercertificate->IsMobileCertificate($mobile)){
				$certificate=$membercertificate->token(false)->where(" mobile=%d AND status=5 ",$mobile)->find();
				$uid=intval($certificate['uid']);
				$userarray=$this->token(false)->where(" uid=$uid ")->find();
				
				//手机验证----------------------------------------------
				$security=$this->MobileSecurity($uid,$userarray,'loginsecurity');
				if(!$security){
					$this->callback='$("#MobileCode").show(500);$("#ShowSecCode").hide();$("#MobileCodeHelp").html("'.$this->error.'").show();';
					return false;
				}
				//------------------------------------------------------
				
				if($userarray['uid']>0){
					$passwordkey=PasswordKey($userarray['username'],$_POST['password'],$userarray['powercode']);
					if($passwordkey==$userarray['password']){
						//权限
						$auth=new \Think\Auth();
						if(!$auth->check(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME,$userarray['uid'])){
							$this->error='对不起!该用户名已被锁定,请联系网站客服解锁!';
							return false;
						}
						
						session('USER_USERID',$userarray['uid']);
						session('USER_USERTYPE',$userarray['usertype']);
						session('USER_USERNAME',$userarray['username']);
				
						return $userarray['uid'];
					}
				}
				if(!$this->LoginError()){
					return false;
				}
				$this->error='对不起!手机不存在或未认证或密码有误!';
				return false;
			}else{
				if(!$this->LoginError()){
					return false;
				}
				$this->error='对不起!手机不存在或未认证或密码有误!';
				return false;
			}

		}elseif(preg_match('/([\w]+)(\@)([\w]+)(\.)([\w]+)/',$_POST['username'])){

			//邮箱
			$email=$_POST['username'];
			if($membercertificate->IsEMailCertificate($email)){
				$certificate=$membercertificate->token(false)->where(" email='%s' AND status=5 ",$email)->find();
				$uid=intval($certificate['uid']);
				$userarray=$this->token(false)->where(" uid=$uid ")->find();
				
				//手机验证----------------------------------------------
				$security=$this->MobileSecurity($uid,$userarray,'loginsecurity');
				if(!$security){
					$this->callback='$("#MobileCode").show(500);$("#ShowSecCode").hide();$("#MobileCodeHelp").html("'.$this->error.'").show();';
					return false;
				}
				//------------------------------------------------------
				
				if($userarray['uid']>0){
			
					$passwordkey=PasswordKey($userarray['username'],$_POST['password'],$userarray['powercode']);
					
					if($passwordkey==$userarray['password']){
						//权限
						$auth=new \Think\Auth();
						if(!$auth->check(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME,$userarray['uid'])){
							$this->error='对不起!该用户名已被锁定,请联系网站客服解锁!';
							return false;
						}
						
						session('USER_USERID',$userarray['uid']);
						session('USER_USERTYPE',$userarray['usertype']);
						session('USER_USERNAME',$userarray['username']);
						
						return $userarray['uid'];
					}
				
				}
				
				$this->error='对不起!邮箱不存在或未认证或密码有误!';
				if(!$this->LoginError()){
					return false;
				}
				return false;
				
			}else{
				$this->error='对不起!邮箱不存在或未认证或密码有误!!';
				if(!$this->LoginError()){
					return false;
				}
				return false;
			}
		
		}elseif(preg_match('/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u',$_POST['username'])){
			
			$member=new \Member\Model\MemberModel();
			
			$username=substr(I('post.username'),0,32);
			
			//UC
			if($uclient=GetClient(array('username'=>$username,'password'=>$_POST['password']))){
					   
				$apiuser=$uclient->user_login();
				
				$uid=intval($apiuser['uid']);
				
				if($uid>0){
					
					$apiuser['username']=$apiuser['name'];
					
					$user=$member->UidGetMember($uid);
					
					if(empty($user['uid'])){
						//注册
						$register=new \Register\Model\MemberModel();
						$register->RegisterMember($apiuser,0);
					}
					
					$this->SetCookies($apiuser);
					
					return $uid;
					
				}else{
					$this->error='对不起!用户名或密码有误!';
					return false;
				}
			}else{
				
				//获取数据
				$userarray=$member->UserNameGetMember($username);

				//手机验证----------------------------------------------
				$security=$this->MobileSecurity(intval($userarray['uid']),$userarray,'loginsecurity');
				if(!$security){
					$this->callback='$("#MobileCode").show(500);$("#ShowSecCode").hide();$("#MobileCodeHelp").html("'.$this->error.'").show();';
					return false;
				}
				//------------------------------------------------------
				
				$passwordkey=PasswordKey($userarray['username'],$_POST['password'],$userarray['powercode']);
				
				if(!empty($userarray['uid']) && $userarray['username']==$_POST['username'] && $passwordkey==$userarray['password']){	
				
					//权限
					$auth=new \Think\Auth();
					if(!$auth->check(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME,$userarray['uid'])){
						$this->error='对不起!该用户名已被锁定,请联系网站客服解锁!';
						return false;
					}

					$this->SetCookies($userarray);
					
					return true;
				}else{
					if(!$this->LoginError()){
						return false;
					}
					$this->error='对不起!用户名或密码有误!!!';
					return false;
				}
			}
		
		}else{
			$this->error='对不起!用户名或密码有误!!';
			return false;
		}
		
		return false;

	}
	
	
	function SetCookies($user=array()){
		session('USER_USERID',$user['uid']);
		session('USER_USERTYPE',$user['usertype']);
		session('USER_USERNAME',$user['username']);
	}
	
	//UC登录
	function UcLogin($uid=0){
		if($uclient=GetClient()){
			$preg=preg_match('/<script.+type=\"text\/javascript\".+src=\"(.*)\".+reload/s',$uclient->login($uid),$match);
			if($preg && !empty($match[1])){
				return $match[1];
			}else{
				return false;
			}
		}
	}
	
	function UcLogout(){
		if($uclient=GetClient()){
			return $uclient->logout();
		}
	}
	
	//登录错误
	function LoginError($islogin=0){
				
		$error='';
		
		//保留最近一天
		$nowtime=NowTime()-(24*60*60);
				
		M('MemberError')->where(" dateline<'$nowtime' ")->delete();

		$loginkey=md5($_POST['username'].GetClientIp());

		$membererrorarr=M('MemberError')->where(" loginkey='$loginkey' ")->field('dateline')->order('id DESC')->find();

		if(!empty($membererrorarr['dateline'])){
			$loginerrortime=$membererrorarr['dateline']+60*intval(C('memberloginerrortime'));
		}else{
			$loginerrortime=0;
		}

		$newtime=time() - 60*intval(C('memberloginerrortime'));
		$loginerrorcount=M('MemberError')->where(" loginkey='$loginkey' AND dateline>'$newtime' ")->order('id DESC')->count();
		if($loginerrorcount>=intval(C('memberloginerrornum'))  && $loginerrortime > time() ){
			$logintime=intval(($loginerrortime-time())/60)+1;
			$this->error='对不起！您输入的错误太多！请 <strong>'.$logintime.'</strong> 分钟后再登录！';
			return false;
		}else{
			if(!$islogin){
				
				M('MemberError')->add(array('loginip'=>GetClientIp(),'loginkey'=>$loginkey,'dateline'=>NowTime()));
				if((intval(C('memberloginerrornum'))-$loginerrorcount) ==0){
					$this->error='对不起！您输入的错误太多！请 <strong>'.intval(C('memberloginerrortime')).'</strong> 分钟后再登录！';
					return false;
				}else{
					$error='用户名或密码有误！';
					if($this->error){
						//$error=$this->error;
					}
					$this->error='<p>'.$error.'您还有 <strong>'.(intval(C('memberloginerrornum'))-$loginerrorcount).'</strong> 机会输入！</p>';
					return false;
				}
			}
		}

		return true;

	}
	
	//返回原页面
	function UrlReferer($referer=''){
		$servername=$_SERVER['SERVER_NAME'];
		if($referer){
			$checkfrom=substr($referer,7,strlen($servername));
		}else{
			$checkfrom=substr($_SERVER['HTTP_REFERER'],7,strlen($servername));
			$referer=$_SERVER['HTTP_REFERER'];
		}
		if($servername!=$checkfrom){
			return U('/');
		}else{
			$refererarray=explode('/',$referer);
			if(in_array('login',$refererarray) || in_array('register',$refererarray)){
				return U('/');
			}else{
				return $referer;
			}
		}
	}
	
}

?>